package com.fieldchain.ex.fa100.utils.net.action;

import android.os.SystemClock;
import android.util.Log;

import com.fieldchain.ex.fa100.inter.StringCallBack;
import com.fieldchain.ex.fa100.utils.net.tools.MainHandler;

import org.json.JSONException;
import org.json.JSONObject;

import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import okhttp3.WebSocket;
import okhttp3.WebSocketListener;

/**
 * Created by biyunlong
 * Email: 1225198434@qq.com
 * Data:  2018/9/27
 */
public class SocketReqst {
    private static WebSocket mWebSocket;
    private static boolean needRestart = true;

    public static void start(final String url, final String send, final OkHttpClient client, final StringCallBack callBack) {
        Request request = new Request.Builder().url(url).build();
        client.newWebSocket(request, new WebSocketListener() {
            @Override
            public void onOpen(WebSocket webSocket, Response response) {
                super.onOpen(webSocket, response);
                Log.e("SocketReqst:", "onOpen");
                mWebSocket = webSocket;
                MainHandler.getInstance().post(new Runnable() {
                    @Override
                    public void run() {
                        boolean isSend = mWebSocket.send(send);
                        Log.e("SocketReqst:", "onOpen" + isSend);
                    }
                });
            }

            @Override
            public void onMessage(WebSocket webSocket, String text) {
                super.onMessage(webSocket, text);
                Log.e("SocketReqst_onMessage:", text);
                try {
                    JSONObject object = new JSONObject(text);
                    callBack.message(object.get("data").toString());
                } catch (JSONException e) {
                    e.printStackTrace();
                }
            }

            @Override
            public void onClosed(WebSocket webSocket, int code, String reason) {
                super.onClosed(webSocket, code, reason);
                Log.e("SocketReqst_onClosed:", code + "  " + reason);
            }

            @Override
            public void onFailure(WebSocket webSocket, Throwable t, Response response) {
                super.onFailure(webSocket, t, response);
                Log.e("SocketReqst_onFailure:", t.toString());
                if (needRestart) {
                    SystemClock.sleep(500);
                    if (!needRestart) return;
                    start(url, send, client, callBack);
                }
            }
        });
        client.dispatcher().executorService().shutdown();
    }

    public static void close() {
        needRestart = true;
        if (mWebSocket != null) {
            mWebSocket.close(1000, "主动关闭");
        }
        mWebSocket = null;
    }
}
